package  app.util.image.action.distort
{
	import app.util.image.action.PartialProcessingAction;
	
	import flash.display.*;
	import flash.filters.*;
	import flash.geom.*;
	
	public class SwirlClockwiseAction extends PartialProcessingAction
	{	
		public override function getDescription():String
		{
			return "Swirl Clockwise";
		}
		
		protected override function doParticalProcess(cur:BitmapData, p:Array, str:Number):BitmapData
		{			
			var ret:BitmapData = cur.clone();
			var angle:Number  = str * Math.PI / 180;
            var width:int = ret.width;
            var height:int = ret.height;
            var mapData:BitmapData = new BitmapData(width, height, false);
            var scale:Number = 256 / (320 / p[2]);
            
            //initialize
            for(var w:int = 0; w < width; w++){
            	for(var h:int = 0; h < height; h++){
            		mapData.setPixel32(w, h, 0x808080);
            	}
            }
            
            var i:int = -p[2];
            var j:int;
            while (i <= p[2])
            {
                j = -p[2];
                while (j <= p[2])
                {
                    var distance:Number = Math.sqrt(i * i + j * j);
                    var ang:Number = Math.atan2(j, i);
                    var px:Number;
                    var py:Number;
                    if (distance >= p[2])
                    {
                        px = i;
                        py = j;
                    }
                    else
                    {
                        var angMinus:Number = angle * ((p[2] - distance) / p[2]) * ((p[2] - distance) / p[2]);
                        px = distance * Math.cos(ang - angMinus);
                        py = distance * Math.sin(ang - angMinus);
                    }
                    px = Math.round(128 + 256 * (px - i) / scale);
                    py = Math.round(128 + 256 * (py - j) / scale);
                    mapData.setPixel32(i + p[0], j + p[1], px << 8 | py);
                    j++;
                }
                i++;
            }
            var distortFilter:DisplacementMapFilter = new DisplacementMapFilter(mapData, new Point(0,0), 
            										 BitmapDataChannel.GREEN, BitmapDataChannel.BLUE, 
            										 scale, scale, DisplacementMapFilterMode.IGNORE);
            ret.applyFilter(ret, ret.rect, new Point(0, 0), distortFilter);
            return ret;

		}
	}
}